// src/ChangeUsername.tsx
import React, { useState } from 'react';
import { Modal, Input, Button, message } from 'antd';

interface ChangeUsernameProps {
  visible: boolean;
  onClose: () => void;
  currentUsername: string;
  onSuccess: (newUsername: string) => void;
}

interface ChangeUsernameRequest {
  currentUsername: string;
  newUsername: string;
}

const ChangeUsername: React.FC<ChangeUsernameProps> = ({
  visible,
  onClose,
  currentUsername,
  onSuccess
}) => {
  const [loading, setLoading] = useState(false);
  const [newUsername, setNewUsername] = useState('');

  const changeUsername = async (requestData: ChangeUsernameRequest): Promise<boolean> => {
    try {
      const token = localStorage.getItem('token') || sessionStorage.getItem('token');
      
      const headers: HeadersInit = {
        'Content-Type': 'application/json',
      };
      
      if (token) {
        headers['Authorization'] = `Bearer ${token}`;
      }

      const response = await fetch('/api/users/change-username', {
        method: 'POST',
        headers,
        body: JSON.stringify(requestData),
      });

      if (response.ok) {
        return true;
      } else {
        let errorMessage = '修改失败，请稍后重试';
        
        try {
          const errorData = await response.json();
          
          if (errorData.message) {
            errorMessage = errorData.message;
          } else if (errorData.error) {
            errorMessage = errorData.error;
          }
          
          if (errorMessage.includes('已存在') || errorMessage.includes('exists')) {
            errorMessage = '该用户名已被使用，请换一个';
          }
        } catch {
          errorMessage = `服务器返回错误 (${response.status})`;
        }
        
        message.error(errorMessage);
        return false;
      }
    } catch (error) {
      console.error('调用用户名修改接口出错:', error);
      message.error('请求发送失败，请稍后重试');
      return false;
    }
  };

  const handleChangeUsername = async () => {
    if (!newUsername.trim()) {
      message.error('用户名不能为空');
      return;
    }

    const trimmedUsername = newUsername.trim();

    if (trimmedUsername.length < 2 || trimmedUsername.length > 20) {
      message.error('用户名长度应在2-20个字符之间');
      return;
    }

    if (trimmedUsername === currentUsername) {
      message.error('新用户名与当前用户名相同');
      return;
    }

    const specialCharRegex = /[<>'"&]/;
    if (specialCharRegex.test(trimmedUsername)) {
      message.error('用户名包含不允许的特殊字符');
      return;
    }

    const usernameRegex = /^[a-zA-Z0-9_]+$/;
    if (!usernameRegex.test(trimmedUsername)) {
      message.error('用户名只能包含字母、数字和下划线');
      return;
    }

    setLoading(true);

    try {
      const requestData: ChangeUsernameRequest = {
        currentUsername,
        newUsername: trimmedUsername
      };

      const success = await changeUsername(requestData);

      if (success) {
        message.success('用户名修改成功，请重新登录');
        onSuccess(trimmedUsername);
        handleClose();
      }
    } catch (error) {
      console.error('修改用户名时发生错误:', error);
      message.error('修改用户名时发生未知错误');
    } finally {
      setLoading(false);
    }
  };

  const handleClose = () => {
    setNewUsername('');
    onClose();
  };

  return (
    <Modal
      title="更改用户名"
      open={visible}
      onCancel={handleClose}
      footer={null}
      width={400}
      destroyOnClose
    >
      <div style={{ marginBottom: '12px' }}>
        <div style={{ fontSize: '14px', color: '#666', marginBottom: '4px' }}>
          当前用户名：{currentUsername}
        </div>
        <Input
          placeholder="请输入新用户名 (2-20个字符，字母、数字、下划线)"
          value={newUsername}
          onChange={(e) => setNewUsername(e.target.value)}
          onPressEnter={handleChangeUsername}
          maxLength={20}
          showCount
          allowClear
        />
      </div>
      <div style={{ fontSize: '12px', color: '#999', marginBottom: '12px' }}>
        提示：用户名修改后需要重新登录
      </div>
      <Button 
        type="primary" 
        block 
        loading={loading}
        onClick={handleChangeUsername}
        disabled={newUsername.trim().length < 2 || !/^[a-zA-Z0-9_]+$/.test(newUsername)}
      >
        {loading ? '修改中...' : '确认修改'}
      </Button>
    </Modal>
  );
};

export default ChangeUsername;